import { NestFactory } from '@nestjs/core';
import { ValidationPipe, BadRequestException } from '@nestjs/common';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './common/response.interceptor';
import { HttpExceptionFilter } from './common/http-exception.filter';
import { formatValidationError } from './common/locale/zh-CN';
import { join } from 'path';
import * as express from 'express';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 应用全局响应拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());
  // 应用全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  // 应用全局验证管道，支持中文错误提示
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // 自动移除未在DTO中定义的属性
      forbidNonWhitelisted: true, // 如果存在未在DTO中定义的属性，则抛出错误
      transform: true, // 自动将请求数据转换为DTO类型
      disableErrorMessages: false, // 显示详细的错误信息
      transformOptions: {
        enableImplicitConversion: true, // 允许隐式类型转换
      },
      exceptionFactory: (errors) => {
        const formattedErrors = errors
          .map(formatValidationError)
          .filter(Boolean);
        throw new BadRequestException({
          statusCode: 400,
          message: '参数验证失败',
          errors: formattedErrors,
        });
      },
    }),
  );
  // 设置全局前缀
  app.setGlobalPrefix('api');

  // 配置静态文件服务，允许前端访问uploads目录中的音乐文件
  const expressAdapter = app.getHttpAdapter();
  // 为带全局前缀和不带全局前缀的请求都提供静态文件服务
  expressAdapter.use(
    '/uploads',
    express.static(join(__dirname, '..', 'uploads')),
  );
  expressAdapter.use(
    '/api/uploads',
    express.static(join(__dirname, '..', 'uploads')),
  );
  await app.listen(process.env.PORT ?? 3001);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
void bootstrap();
